package com.wdg.service.impl;

import com.wdg.dao.ICookBookDao;
import com.wdg.pojo.*;
import com.wdg.service.ICookBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@Service
public class CookBookServiceImpl implements ICookBookService {

    @Autowired
    public ICookBookDao cookBookDao;

    @Override
    @Transactional //如果出错就回滚
    public int addCookBook(Cookbook cookbook) {

        /**
         * 生成菜谱的主键,并设置进菜谱
         */

        String cbid = UUID.randomUUID().toString().replace("-","");

        System.out.println(cbid);
        cookbook.setCbid(cbid);

        int i1 = addFoodStatus(cbid);
        if (i1 > 0)
        /**
         * 将菜谱主键设置到步骤了里面，并且循环的将步骤加入到步骤表中，tb_details
         */
        for (Details d : cookbook.getDetailsList()) {

            if(!d.getImage().isEmpty()){
                d.setCbid(cbid);

                int i = addCBStep(d);

                if(i < 0)  return i;
            }

        }
        /**
         * 将菜谱的主键设置进主料和辅料的cbid中，并主料和辅料遍历加入到数据库tb_main，tb_trim
         */
        for (Cbmain cbm : cookbook.getCbmainList()) {
            if (!cbm.getMain().trim().isEmpty()&&!cbm.getLevels().trim().isEmpty()){//不为空就加入
                cbm.setCbid(cbid);

                int i = addMain(cbm);

                if(i < 0)  return i;
            }
        }

        for (Cbtrim cbt : cookbook.getCbtrimList()) {

            if(!cbt.getTrims().trim().isEmpty() && !cbt.getLevels().trim().isEmpty()){
                cbt.setCbid(cbid);

                int i = addTrim(cbt);

                if(i < 0)  return i;
            }
        }
        /**
         * 将菜谱的主键和拿到的工具的id加入到它们的中间表中
         */
        for (Cbtool cbt : cookbook.getCbtoolList()) {

            Map<String ,Object> toolMap = new HashMap<>();

            int cbtoid = cbt.getCbtoid();
            System.out.println(cbtoid);
            toolMap.put("cbid",cbid);

            toolMap.put("cbtoid",cbtoid);

            int i = addTool(toolMap);

            if (i < 0) return i;
        }

        return cookBookDao.addCookBook(cookbook);//将cookbook加入到tb_cookbook中
    }

    @Override
    public int addCBStep(Details details) {
        return cookBookDao.addCBStep(details);
    }

    @Override
    public int addMain(Cbmain cbmain) {
        return cookBookDao.addMain(cbmain);
    }

    @Override
    public int addTrim(Cbtrim cbtrim) {
        return cookBookDao.addTrim(cbtrim);
    }

    @Override
    public int addTool(Map cbtool) {
        return cookBookDao.addTool(cbtool);
    }

    @Override
    public int addFoodStatus(String cbdid) {
        return cookBookDao.addFoodStatus(cbdid);
    }
}
